/****
	Copyright 2011 Taras Kulbachka

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

		http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/
package com.atdevsoft.apps.abyss;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class DownloadActivity extends Activity {
	private static final int DEFAULT_PAGES_COUNT = 3;	
	
	private Button mBtnStart;
	private Button mBtnClose;	
	private EditText mEtPagesCount;
	private ProgressBar mPbProgress;
	private TextView mTvProgress;	
	private CheckBox mCbStopOnDup;	
	private CheckBox mCbFastDownload;		

	
	private Context mContext;
	private Activity mThisActivity;	
	
	private int mPagesCount;
	
	private BroadcastReceiver pingbackReceiver = new BroadcastReceiver() {        
	    @Override
	    public void onReceive(Context context, Intent intent) {
	    	mBtnStart.setEnabled(true);	    	
	    }
	};

	
	private BroadcastReceiver pageDoneReceiver = new BroadcastReceiver() {        
	    @Override
	    public void onReceive(Context context, Intent intent) {
	    	
	    	String pageName = intent.getExtras().getString(AbyssDownloaderService.INTENT_EXTRA_PAGE_NAME);
	    	int quotesAdded = intent.getExtras().getInt(AbyssDownloaderService.INTENT_EXTRA_QUOTES_ADDED);
	    	int quotesSkipped = intent.getExtras().getInt(AbyssDownloaderService.INTENT_EXTRA_QUOTES_SKIPPED);
	    	
	    	int percentDone = intent.getExtras().getInt(AbyssDownloaderService.INTENT_EXTRA_PRECENT_DONE);
	    	mPbProgress.setProgress(percentDone);
	    	
	        mTvProgress.setText(String.format(context.getString(R.string.download_progress_data), pageName, quotesAdded, quotesSkipped));
	    }
	};
	
	private BroadcastReceiver downloadDoneReceiver = new BroadcastReceiver() {        
	    @Override
	    public void onReceive(Context context, Intent intent) {
	    	int resultCode = intent.getExtras().getInt(AbyssDownloaderService.INTENT_EXTRA_RESULT_CODE);
	    	int totalQuotesAdded = intent.getExtras().getInt(AbyssDownloaderService.INTENT_EXTRA_QUOTES_ADDED);
	    	int totalQuotesSkipped = intent.getExtras().getInt(AbyssDownloaderService.INTENT_EXTRA_QUOTES_SKIPPED);
	    	
	    	if ((resultCode == AbstractQuoteDownloader.STATUS_ABORT) && (totalQuotesSkipped > 0)) {
				Toast t = Toast.makeText(mContext, mContext.getString(R.string.nothing_to_add), Toast.LENGTH_LONG);
		        t.show();
			} else if (totalQuotesAdded > 0) {
				Toast t = Toast.makeText(mContext, String.format(mContext.getString(R.string.download_finished), totalQuotesAdded), Toast.LENGTH_LONG);
		        t.show();
		        mThisActivity.setResult(RESULT_OK);
		        mThisActivity.finish();
	        } else {
				Toast t = Toast.makeText(mContext, mContext.getString(R.string.no_quotes), Toast.LENGTH_LONG);
		        t.show();					        	
	        }	        
	    	
			mBtnStart.setEnabled(true);
	    }
	};	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_download);

        LayoutParams params = getWindow().getAttributes(); 
        params.width = LayoutParams.FILL_PARENT; 
        getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);        
        
        mContext = this;
        mThisActivity = this;
        mBtnStart = (Button)findViewById(R.id.btn_ok);
        mBtnClose = (Button)findViewById(R.id.btn_close);      
        mPbProgress = (ProgressBar)findViewById(R.id.pb_progress);
        mEtPagesCount = (EditText)findViewById(R.id.et_pages_count);
        mTvProgress = (TextView)findViewById(R.id.tv_progress);
        mCbStopOnDup = (CheckBox)findViewById(R.id.cb_stop_on_dup);
        mCbFastDownload = (CheckBox)findViewById(R.id.cb_fast_download);        

        mCbStopOnDup.setEnabled(!mCbFastDownload.isChecked());	
        
        mBtnClose.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();				
			}
		});
        
        mBtnStart.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {				
				mBtnStart.setEnabled(false);
		        try {
		        	mPagesCount = Integer.parseInt(mEtPagesCount.getText().toString());
		        } catch (NumberFormatException e) {
		        	mPagesCount = DEFAULT_PAGES_COUNT;
		        }
		        mPbProgress.setMax(100);
		        mPbProgress.setProgress(0);
		        
		        Intent i = new Intent(mContext, AbyssDownloaderService.class);
		        i.setAction(AbyssDownloaderService.ACTION_DOWNLOAD_ABYSS_QUOTES);
		        i.putExtra(AbyssDownloaderService.INTENT_EXTRA_PAGES_COUNT, mPagesCount);
		        i.putExtra(AbyssDownloaderService.INTENT_EXTRA_STOP_ON_DUPLICATE, mCbStopOnDup.isChecked());
		        i.putExtra(AbyssDownloaderService.INTENT_EXTRA_FAST_DOWNLOAD, mCbFastDownload.isChecked());
		        startService(i);		        
			}
		});       
        
        mCbFastDownload.setOnCheckedChangeListener(new OnCheckedChangeListener() {			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				mCbStopOnDup.setEnabled(!isChecked);				
			}
		});        
        
    }
    
    @Override
    protected void onResume() {
        super.onResume();   
        registerReceiver(pingbackReceiver, new IntentFilter(AbyssDownloaderService.ACTION_PINGBACK_IDLE));
        registerReceiver(pageDoneReceiver, new IntentFilter(AbyssDownloaderService.ACTION_DOWNLOAD_PAGE_DONE));
        registerReceiver(downloadDoneReceiver, new IntentFilter(AbyssDownloaderService.ACTION_DOWNLOAD_ALL_DONE));
        
        mBtnStart.setEnabled(false);
        
        Intent i = new Intent(mContext, AbyssDownloaderService.class);
        i.setAction(AbyssDownloaderService.ACTION_PING_IS_DOWNLOADING);        
        startService(i);
    }
    
    @Override
    protected void onPause() {
        super.onPause();        
        unregisterReceiver(pingbackReceiver);
        unregisterReceiver(pageDoneReceiver);
        unregisterReceiver(downloadDoneReceiver);
    }    
    
}